package com.base.myproject.client.busi.BO;

import java.io.Serializable;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import com.base.myproject.client.jdbc.StoreInfo;
import com.extjs.gxt.ui.client.data.ModelData;
import com.extjs.gxt.ui.client.store.TreeStore;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.treepanel.TreePanel;
import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.rpc.AsyncCallback;

/**
 * 构造treestore的modeldata
 * @author Administrator
 *2010-4-30
 * javazgw@gmail.com
 */
public class TreeNodeModelData extends
		com.extjs.gxt.ui.client.data.BaseTreeModel implements Serializable,
		CellType, SetGetValue, InsertDeleteUpdate {

	/**
	 * 
	 */
	private static final long serialVersionUID = 3241266083171056766L;

	public TreeNodeModelData parentnode;

	StoreInfo storeinfo;
	int busistatus = 1;
	protected java.util.Map<String, Object> keyoldvalue = new java.util.HashMap<String, Object>();
	public TreeNodeModelData() {

	}

	public TreeNodeModelData(StoreInfo storeinfo) {
		this(storeinfo,false);
		
	}

	public TreeNodeModelData(ModelData model) {

	}
	public TreeNodeModelData(StoreInfo storeinfo,boolean isnew) {
		this.storeinfo = storeinfo;
		if(isnew)
		{
			addnewRecord(storeinfo,"","");
		}
	}

	public void addnewRecord(StoreInfo storeinfo,String columnname,String columnvalue)
	{
		com.base.myproject.client.tools.GreetingServiceAsync greetingService = GWT
		.create(com.base.myproject.client.tools.GreetingService.class);
		greetingService.getIcode(storeinfo, columnname, columnvalue, new AsyncCallback<String>(){

			@Override
			public void onFailure(Throwable caught) {
				MessageBox.alert("错误", "网络发生断裂，添加记录失败！", null);
				
			}

			@Override
			public void onSuccess(String result) {
				setNotFlag("icode", result);
				//设置老值，否则组织sql有错误。
				put("icode",result);
				
			}
			
		});
		
	}
	LinkedList<TreeNodeModelData> allll = new LinkedList<TreeNodeModelData>();

	public void addNodeSort(TreeNodeModelData node) {
		TreeNodeModelData ntemp = this;
		int len = 0;
		// listall(this);

		for (TreeNodeModelData n : allll) {
			if (node.get(getSortcolumn()).toString().startsWith(
					n.get(getSortcolumn()).toString())) {
				// len = n.toString().length()>len?n.toString().length():len;
				if (n.get(getSortcolumn()).toString().length() > len) {
					len = n.get(getSortcolumn()).toString().length();
					ntemp = n;
				}
			}
		}
		allll.add(node);
		ntemp.add(node);

	}

	public String toString() {
		return this.get("id");
	}

	public String getSortcolumn() {
		return storeinfo.getTreesortcolumn();
	}

	public void setSortcolumn(String sortcolumn) {
		storeinfo.setTreesortcolumn(sortcolumn);
		
	}


	public static void main(String[] argv) {
//		TreeNodeModelData b1 = new TreeNodeModelData("id");
//		b1.set("id", "1001");
//		TreeNodeModelData b2 = new TreeNodeModelData("id");
//		b2.set("id", "100101");
//		TreeNodeModelData b3 = new TreeNodeModelData("id");
//		b3.set("id", "100102");
//		TreeNodeModelData b4 = new TreeNodeModelData("id");
//		b4.set("id", "100103");
//
//		TreeNodeModelData b5 = new TreeNodeModelData("id");
//		b5.set("id", "1002");
//		TreeNodeModelData b6 = new TreeNodeModelData("id");
//		b6.set("id", "1003");
//		TreeNodeModelData b7 = new TreeNodeModelData("id");
//		b7.set("id", "100301");
//		TreeNodeModelData b8 = new TreeNodeModelData("id");
//		b8.set("id", "100306");
//
//		TreeNodeModelData root = new TreeNodeModelData("id");
//		root.set("id", "1");
//
//		root.addNodeSort(b1);
//		root.addNodeSort(b2);
//		root.addNodeSort(b3);
//		root.addNodeSort(b4);
//		root.addNodeSort(b5);
//		root.addNodeSort(b6);
//		root.addNodeSort(b7);
//		root.addNodeSort(b8);
//
//		System.out.println("--");
		// System.out.println(root.listNodeName(root,""));
	}

	int celldatatype = 0;

	@Override
	public int getCellDataType() {

		return celldatatype;
	}

	@Override
	public void setCellDataType(int celltype) {

		this.celldatatype = celltype;
	}

	@Override
	public void clearBusistatus()
	{
		this.busistatus =NOTHING;
	}

	@Override
	public int getBusistatus() {
		return busistatus;
	}

	@Override
	public void removeBusistatus(int status)
	{
		this.busistatus =this.busistatus & status;
	}

	@Override
	public void setBusistatus(int status) {

		this.busistatus =this.busistatus | status;
	}
/**
 * 赋值，客户端使用。
 */
	public <X> X set(String property, X value) {
		setBusistatus(UPDATE);


		return setNotFlag(property, value);
		//return super.set(property, value);

	}
/**
 * 服务器初始化的时候调用，其他情况不要使用。
 * @param <X>
 * @param property
 * @param value
 * @return
 */
	public <X> X setNotFlagInit(String property, X value) {
		/**
		 * 读入数据时，设置主键的原始值，方便update，delete
		 */
		for(String key:storeinfo.getKeyname())
		{
			if(key.equals(property))
				put(key,value);
		}
		return setNotFlag( property, value);
	}
	/**
	 * 赋值
	 */
	@Override
	public <X> X setNotFlag(String property, X value) {
	
		
		switch (celldatatype) {
		case TYPE_STRING:
			return super.set(property, value);
			
		case TYPE_INT:
			return super.set(property, value);
			
		case TYPE_DOUBLE:
			return super.set(property, value);
			
		case TYPE_DATE:

			return super.set(property, value);
		case TYPE_LONG:

			return super.set(property, value);

		case TYPE_FLOAT:

			return super.set(property, value);
		case TYPE_BOOLEAN:

			return super.set(property, value);

		default:
			return super.set(property, value);
		}
	}

	@Override
	public String delete() {

		if(keyoldvalue.size()==0)
		{
			return null;
		}
		StringBuffer deletesql = new StringBuffer();
		deletesql.append("delete "+storeinfo.getTablename()+ " where ");
		Iterator<String> keyiterator = keyoldvalue.keySet().iterator();
		while(keyiterator.hasNext())
		{
			String key = keyiterator.next();
			Object value = getKeyOldValue(key);
			if(value==null)
				deletesql.append("  "+key+" is null  and");
			else
			deletesql.append("  "+key+"='"+value+"' and");
		}
		//去掉最后的 and
		deletesql = deletesql.replace(deletesql.length()-3, deletesql.length(), "");
		
		//GWT.log(deletesql, null);
		return new String(deletesql);
	
	}

	@Override
	public String insert() {

		StringBuffer insertsql =new StringBuffer();
		insertsql.append("insert into "+storeinfo.getTablename());
		insertsql.append(" (");
		
		Iterator<String> iterator = this.getPropertyNames().iterator();
		StringBuffer sbvalue = new StringBuffer();
		while(iterator.hasNext())
		{
			
			String key = iterator.next();
			
			
			if(get(key) instanceof ModelData)
			{
				Object o=((ModelData)get(key)).get("code");
				if(o==null)
				{
					insertsql.append(""+key+",");
					sbvalue.append("null,");
				}
				else
				{
					insertsql.append(""+key+",");
					sbvalue.append("'"+o+"',");
				}
			}
			else
			{
			insertsql.append(""+key+",");
			sbvalue.append("'"+get(key)+"',");
			}
		}
		insertsql = insertsql.replace(insertsql.length()-1, insertsql.length(), "");
		sbvalue = sbvalue.replace(sbvalue.length()-1, sbvalue.length(), "");
		insertsql.append(" ) values(");
		insertsql.append(sbvalue+")");
//		for(int i=0;i<this.getPropertyNames().size();i++)
//		{
//			insertsql +=""+this.getPropertyNames().iterator();
//		}
		return new String (insertsql);
	
	}

	@Override
	public String update() {

		StringBuffer updatesql = new StringBuffer();
		updatesql.append("update " +storeinfo.getTablename()+" set ");
		Iterator<String> iterator = this.getPropertyNames().iterator();
		Class c ;
		DateTimeFormat activeFormat = DateTimeFormat
		.getFormat("yyyy-MM-dd HH:mm:ss");
		while(iterator.hasNext())
		{
			String key = iterator.next();
			if(key.equals("icode"))
			{
				continue;
			}
				
			if(keyoldvalue.containsKey(key))
			{
				if(get(key)!=null && !(get(key).equals(keyoldvalue.get(key))))
					updatesql.append(""+key+"='"+get(key)+"',");
				
//				if(get(key)==null)
//				{
//					updatesql.append(""+key+"=null,");
//				}
//				else if(!(get(key).equals(keyoldvalue.get(key))))
//				{
//					updatesql.append(""+key+"='"+get(key)+"',");
//				}
				
			}
			else 
			{
				/**
				 * 此处专门负责储存的值是modeldata类型诸如 combox 
				 */
				if(get(key) instanceof ModelData)
				{
					Object o=((ModelData)get(key)).get("code");
					if(o==null)
					{
					updatesql.append(""+key+"=null,");
					}
					else
					{
						updatesql.append(""+key+"='"+o+"',");
					}
				}
				else
				{
					if(get(key)==null)
					{
						updatesql.append(""+key+"=null,");
					}
					else
					{
						c = get(key).getClass();
						//Debug.printf("key = "+key +" value = "+ get(key) +" class =" + get(key).getClass(), 4);
						if(c.equals(Integer.class))
						{
							updatesql.append(""+key+"="+get(key)+",");
						}
						else if(c.equals(Long.class))
						{
							updatesql.append(""+key+"="+get(key)+",");
						}
						else if(c.equals(Float.class))
						{
							updatesql.append(""+key+"="+get(key)+",");
						}
						else if(c.equals(Date.class))
						{
							if(get(key)!=null)
							{
								
								updatesql.append(""+key+"='"+activeFormat.format((Date)get(key))+"',");
							}
							
							else
								updatesql.append(""+key+"=null ,");
							
						}
						else if(c.equals(Double.class))
						{
							updatesql.append(""+key+"="+get(key)+",");
						}
						else if(c.equals(Boolean.class))
						{
							if(((Boolean)get(key))==true)
							updatesql.append(""+key+"=1,");
							else
								updatesql.append(""+key+"=0,");
						}
						else
						{
							updatesql.append(""+key+"='"+get(key)+"',");
						}
						
					//	System.out.println(get(key).getClass());
						//Debug.printf("key="+key +"  class = "+ get(key).getClass(), 3);
						
					//	updatesql.append(""+key+"='"+get(key)+"',");
					}
				}
			}
			
			
		}
		updatesql = updatesql.replace(updatesql.length()-1, updatesql.length(), "");
		
		updatesql.append(" where ");
		Iterator<String> keyiterator = keyoldvalue.keySet().iterator();
		while(keyiterator.hasNext())
		{
			String key = keyiterator.next();
			Object value = getKeyOldValue(key);
			
			updatesql.append("  "+key+"='"+value+"' and");
		}
		//去掉最后的 and
		updatesql = updatesql.replace(updatesql.length()-3, updatesql.length(), "");
		
		//updatesql +=" where icode='"+getIcode()+"'";
		GWT.log(""+updatesql, null);
		//Window.alert("updatesql="+updatesql+" \n " +this.getPropertyNames());
		return new String(updatesql);
	
	}
	
	
	/**
	 * @param keyoldvalue the keyoldvalue to set
	 */
	public void setKeyoldvalue(java.util.Map<String, Object> keyoldvalue) {
		this.keyoldvalue = keyoldvalue;
	}

	/**
	 * 设置主键原始值
	 * @param key
	 * @param value
	 */
	public void put(String key,Object value)
	{
		keyoldvalue.put(key, value);
		
	}
	/**
	 * 获得某个主键的原始值
	 * @param key
	 * @return
	 */
	
	public Object getKeyOldValue(String key)
	{
		if(keyoldvalue.containsKey(key))
		return keyoldvalue.get(key);
		else
			return null;
	}

	public StoreInfo getStoreinfo() {
		return storeinfo;
	}

	public void setStoreinfo(StoreInfo storeinfo) {
		this.storeinfo = storeinfo;
	}
	
	
//	public TreePanel aa() {
//		TreeNodeModelData b1 = new TreeNodeModelData("id");
//		b1.set("id", "1001");
//		b1.setSortcolumn("id");
//		TreeNodeModelData b2 = new TreeNodeModelData("id");
//		b2.set("id", "100101");
//		TreeNodeModelData b3 = new TreeNodeModelData("id");
//		b3.set("id", "100102");
//		TreeNodeModelData b4 = new TreeNodeModelData("id");
//		b4.set("id", "100103");
//
//		TreeNodeModelData b5 = new TreeNodeModelData("id");
//		b5.set("id", "1002");
//		TreeNodeModelData b6 = new TreeNodeModelData("id");
//		b6.set("id", "1003");
//		TreeNodeModelData b7 = new TreeNodeModelData("id");
//		b7.set("id", "100301");
//		TreeNodeModelData b8 = new TreeNodeModelData("id");
//		b8.set("id", "100306");
//
//		TreeNodeModelData root = new TreeNodeModelData("id");
//		root.set("id", "1");
//
//		b1.setSortcolumn("id");
//		b2.setSortcolumn("id");
//		b3.setSortcolumn("id");
//		b4.setSortcolumn("id");
//		b5.setSortcolumn("id");
//		b6.setSortcolumn("id");
//		b7.setSortcolumn("id");
//		b8.setSortcolumn("id");
//		root.addNodeSort(b1);
//		root.addNodeSort(b2);
//		root.addNodeSort(b3);
//		root.addNodeSort(b4);
//		root.addNodeSort(b5);
//		root.addNodeSort(b6);
//		root.addNodeSort(b7);
//		root.addNodeSort(b8);
//
//		// b1.add(b2);
//
//		root.set("name", "name111");
//		TreeStore store = new TreeStore();
//		store.add(root, true);
//		// store.add(root.getChildren(), true);
//		System.out.println(store.getChildCount());
//		final TreePanel<TreeNodeModelData> tree = new TreePanel<TreeNodeModelData>(
//				store);
//		tree.setHeight(100);
//		tree.setDisplayProperty("id");
//
//		return tree;
//	}

}
